//
//  JYTNFCOperate.m
//  JYTNFCCore
//
//  Created by 九爷 on 2024/1/17.
//

#import "JYTNFCOperate.h"

#import "JYTNFCApi.h"
#import "JYTNFCCoreTool.h"

#import <JYTMacros.h>
#import <JYTAlertView.h>
#import <CoreNFC/CoreNFC.h>
#import <LYExtension/LYExtension.h>

typedef NS_ENUM(NSUInteger, JYTNFCOptStatus) {
    JYTNFCOptStatusNone,
    JYTNFCOptStatusBegin,
    JYTNFCOptStatusIng,
    JYTNFCOptStatusFinish,
};

API_AVAILABLE(ios(13.0))
@interface JYTNFCOperate () <NFCTagReaderSessionDelegate>

@property (nonatomic, assign, readonly) BOOL isNFCSuccess;
@property (nonatomic, assign, readonly) BOOL isNormalCard;
@property (nonatomic, assign, readonly) BOOL isGary;
@property (nonatomic, assign, readonly) JYTNFCOptStatus optStatus;
@property (nonatomic, assign, readonly) JYTNFCOptType optType;
@property (nonatomic, copy, readonly) NSString *rechargeFee;
@property (nonatomic, copy, readonly) NSString *rechargeOrderId;
@property (nonatomic, copy, readonly) NSString *rechargeCardNo;
@property (nonatomic, copy, readonly) NSString *cardNo;
@property (nonatomic, copy, readonly) NSString *cardBalance;
@property (nonatomic, copy, readonly) NSString *cityCode;
@property (nonatomic, copy, readonly) NSString *cardStatusStr;
@property (nonatomic, copy, readonly) NSString *cardTypePath;
@property (nonatomic, copy, readonly) NSString *optErrorStr;
@property (nonatomic, copy, readonly) JYTNFCReadCardComplation readComplation;
@property (nonatomic, copy, readonly) JYTNFCWriteCardComplation writeComplation;
@property (nonatomic, strong) JYTNFCApi *api;
@property (nonatomic, strong) id<NFCISO7816Tag> effective7816Tag;
@property (nonatomic, strong) NFCTagReaderSession *nfcSession;
@property (nonatomic, strong) NSMutableDictionary *prepareCmdResultDict;

@end

@implementation JYTNFCOperate

- (instancetype)init {
    self = [super init];
    if (self) {
        [self _changeOptType:JYTNFCOptTypeRead];
        [self _changeOptStatus:JYTNFCOptStatusNone];
        _isNFCSuccess = NO;
        _isGary = NO;
    }
    return self;
}

+ (void)isDebugEnv:(BOOL)isDebugEnv {
    [[JYTNFCCoreTool instance] setDebugEnv:isDebugEnv];
}

+ (BOOL)canUseNfc {
    if (@available(iOS 13.0, *)) {
        return NFCTagReaderSession.readingAvailable;
    }
    return NO;
}

- (void)jytReadCard:(JYTNFCReadCardComplation)complation {
    _readComplation = complation;
    _cardStatusStr = @"";
    _optErrorStr = @"";
    
    if (@available(iOS 13.0, *)) {
        if (self.nfcSession) {
            self.effective7816Tag = nil;
            self.nfcSession = nil;
        }
        self.nfcSession = [[NFCTagReaderSession alloc] initWithPollingOption:NFCPollingISO14443 delegate:self queue:dispatch_get_main_queue()];
        
        self.nfcSession.alertMessage = @"请将公交卡放置在手机背后摄像头附近的位置";
        
        @kWeakify(self);
        [self.api login:^(BOOL isSuccess, NSString *error) {
            @kStrongify(self);
            if (isSuccess) {
                [self _changeOptType:JYTNFCOptTypeRead];
                kGCD_Main_block(^{
                    [self.nfcSession beginSession]; //开始识别 弹出识别提示框
                });
            } else {
                kGCD_Main_block(^{
                    JYTAlertView *alert = [[JYTAlertView alloc] initWithTitle:@"NFC" content:error];
                    [alert setAligment:JYTAlertContentAligmentCenter];
                    JYTAlertAction *cancelAct = [[JYTAlertAction alloc] initWithTitle:@"取消" style:JYTAlertActionStyleBlack complation:NULL];
                    [alert addAction:cancelAct];
                    JYTAlertAction *repetAct = [[JYTAlertAction alloc] initWithTitle:@"重试" style:JYTAlertActionStyleVI complation:^{
                        kGCD_Async_block(^{
                            [self jytReadCard:complation];
                        });
                    }];
                    [alert addAction:repetAct];
                    [alert show];
                });
            }
        }];
    }
}

- (void)jytWriteCardWithRechargeFee:(NSString *)rechargeFee orderId:(NSString *)orderId cardNo:(NSString *)cardNo complation:(JYTNFCWriteCardComplation)complation {
    _writeComplation = complation;
    _rechargeFee = rechargeFee;
    _rechargeOrderId = orderId;
    _rechargeCardNo = cardNo;
    _cardStatusStr = @"";
    _optErrorStr = @"";
    
    if (@available(iOS 13, *)) {
        if (self.nfcSession) {
            self.effective7816Tag = nil;
            self.nfcSession = nil;
        }
        self.nfcSession = [[NFCTagReaderSession alloc] initWithPollingOption:NFCPollingISO14443 delegate:self queue:dispatch_get_main_queue()];
        self.nfcSession.alertMessage = @"请将公交卡放置在手机背后摄像头附近的位置";
        
        @kWeakify(self);
        [self.api login:^(BOOL isSuccess, NSString *error) {
            @kStrongify(self);
            if (isSuccess) {
                [self _changeOptType:JYTNFCOptTypeWrite];
                kGCD_Main_block(^{
                    [self.nfcSession beginSession]; //开始识别 弹出识别提示框
                });
            } else {
                kGCD_Main_block(^{
                    JYTAlertView *alert = [[JYTAlertView alloc] initWithTitle:@"NFC" content:error];
                    [alert setAligment:JYTAlertContentAligmentCenter];
                    JYTAlertAction *cancelAct = [[JYTAlertAction alloc] initWithTitle:@"取消" style:JYTAlertActionStyleBlack complation:NULL];
                    [alert addAction:cancelAct];
                    JYTAlertAction *repetAct = [[JYTAlertAction alloc] initWithTitle:@"重试" style:JYTAlertActionStyleVI complation:^{
                        kGCD_Async_block(^{
                            [self jytWriteCardWithRechargeFee:rechargeFee orderId:orderId cardNo:cardNo complation:complation];
                        });
                    }];
                    [alert addAction:repetAct];
                    [alert show];
                });
            }
        }];
    }
}

- (void)jytRevertCard:(JYTNFCWriteCardComplation)complation {
    _writeComplation = complation;
    if (@available(iOS 13, *)) {
        if (self.nfcSession) {
            self.effective7816Tag = nil;
            self.nfcSession = nil;
        }
        self.nfcSession = [[NFCTagReaderSession alloc] initWithPollingOption:NFCPollingISO14443 delegate:self queue:dispatch_get_main_queue()];
        self.nfcSession.alertMessage = @"请将公交卡放置在手机背后摄像头附近的位置";
        
        @kWeakify(self);
        [self.api login:^(BOOL isSuccess, NSString *error) {
            @kStrongify(self);
            if (isSuccess) {
                [self _changeOptType:JYTNFCOptTypeExceptRevert];
                kGCD_Main_block(^{
                    [self.nfcSession beginSession]; //开始识别 弹出识别提示框
                });
            } else {
                kGCD_Main_block(^{
                    JYTAlertView *alert = [[JYTAlertView alloc] initWithTitle:@"NFC" content:error];
                    [alert setAligment:JYTAlertContentAligmentCenter];
                    JYTAlertAction *cancelAct = [[JYTAlertAction alloc] initWithTitle:@"取消" style:JYTAlertActionStyleBlack complation:NULL];
                    [alert addAction:cancelAct];
                    JYTAlertAction *repetAct = [[JYTAlertAction alloc] initWithTitle:@"重试" style:JYTAlertActionStyleVI complation:^{
                        kGCD_Async_block(^{
                            [self jytRevertCard:complation];
                        });
                    }];
                    [alert addAction:repetAct];
                    [alert show];
                });
            }
        }];
    }
}

- (void)tagReaderSessionDidBecomeActive:(NFCTagReaderSession *)session API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    [self _changeOptStatus:JYTNFCOptStatusBegin];
}

- (void)tagReaderSession:(NFCTagReaderSession *)session didDetectTags:(NSArray<__kindof id<NFCTag>> *)tags API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    [self _changeCardType:@""];
    if (tags.count > 1) {
        [self _failReadCardWithError:@"识别到多个卡片，请选择正确的卡片并重试!"];
        return;
    }
    
    id<NFCTag> tag = tags[0];
    if (tag.type != 3) {
        [self _failReadCardWithError:@"该卡不能进行相关操作!"];
        return;
    }
    
    id<NFCISO7816Tag> tmpTag = [tags[0] asNFCISO7816Tag];
    
    if (tmpTag) {
        @kWeakify(self);
        [self.nfcSession connectToTag:tmpTag completionHandler:^(NSError * _Nullable error) {
            @kStrongify(self);
            if (error) {
                self.effective7816Tag = nil;
                [self _failReadCardWithError:@"读卡失败，请稍后重试"];
            } else {
                [self _changeOptStatus:JYTNFCOptStatusIng];
                self.effective7816Tag = tmpTag;
                NSString *ats = [JYTNFCCoreTool convertApduListDataToHexStr:self.effective7816Tag.historicalBytes];
                NSLog(@"historicalBytes 长度:%@", @(self.effective7816Tag.historicalBytes.length));
                NSString *uid = [JYTNFCCoreTool convertApduListDataToHexStr:self.effective7816Tag.identifier];
                NSString *aid = self.effective7816Tag.initialSelectedAID;
                NSLog(@"ATS %@", ats);
                NSLog(@"CSN %@", uid);
                NSLog(@"AID %@", aid);
                
                if ([NSString lyIsEmptyStr:ats]) {
                    [self _failReadCardWithError:@"该卡不能进行相关操作!"];
                    return;
                }
                
                if ([aid isEqualToString:JYT_NFC_TAG_CARD_AID_JTB]) {
                    [self _changeCardType:@"JTB"];
                }
                
                if ([aid hasPrefix:JYT_NFC_TAG_CARD_AID_LOCAL]) {
                    [self _changeCardType:@"LOCAL"];
                }
                
                if ([NSString lyIsEmptyStr:self.cardTypePath]) {
                    self.effective7816Tag = nil;
                    [self _failReadCardWithError:@"读卡失败，请稍后重试"];
                } else {
                    self.nfcSession.alertMessage = @"已识别到卡片，请勿移动卡片。";
                    [self.prepareCmdResultDict removeAllObjects];
                    
                    NSArray *adpus = @[@{@"apdu":@"00A4040008A000000632010105", @"type":@"checkAndReturn", @"name":@"readOrg"}, @{@"apdu":@"00b0950000", @"type":@"checkAndReturn", @"name":@"getOrg"}];
                    if ([aid isEqualToString:JYT_NFC_TAG_CARD_AID_JTB]) {
                        kGCD_Async_block((^{
                            [self _processAdpus:adpus complation:^(BOOL finish) {
                                if (finish) {
                                    //判断是不是城卡交通部01396900机构标识
                                    if ([[NSString lyFormatStr:[self.prepareCmdResultDict lyObjectForKey:@"getOrg"]] hasPrefix:@"01396900"]) {
                                        //是继续后面操作
                                        [self.prepareCmdResultDict removeAllObjects];
                                        [self _startNFCOptWithATS:ats UID:uid];
                                    } else {
                                        //不是提示不能操作
                                        [self _failReadCardWithError:@"该卡不能进行相关操作!"];
                                    }
                                } else {
                                    [self _failReadCardWithError:@"读卡失败，请稍后重试"];
                                }
                            }];
                        }));
                    } else {
                        [self _startNFCOptWithATS:ats UID:uid];
                    }
                }
            }
        }];
    } else {
        self.effective7816Tag = nil;
        [self _failReadCardWithError:@"读卡失败，请稍后重试"];
    }
}

- (void)tagReaderSession:(NFCTagReaderSession *)session didInvalidateWithError:(NSError *)error API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    NSLog(@"%@", error.localizedDescription);
//    NFCReaderError *nfcerror = (NFCReaderError *)error;
    NSString *errorStr = [NSString stringWithFormat:@"出错了，请稍后重试[%@]", @(error.code)];
    if (self.isNFCSuccess) {
        errorStr = [NSString lyIsEmptyStr:self.cardStatusStr] ? errorStr : self.cardStatusStr;
    } else {
        errorStr = [NSString lyIsEmptyStr:self.optErrorStr] ? errorStr : self.optErrorStr;
    }
    
    BOOL resultSuccess = NO;
    switch (self.optStatus) {
        case JYTNFCOptStatusFinish:
            resultSuccess = self.isNFCSuccess;
            break;
        default:
            resultSuccess = NO;
            break;
    }
    
    switch (self.optType) {
        case JYTNFCOptTypeRead:
            !self.readComplation ?: self.readComplation(resultSuccess, errorStr, self.cardNo, self.cardBalance, self.cityCode, self.isNormalCard, self.cardStatusStr, self.optStatus == JYTNFCOptStatusBegin);
            break;
        case JYTNFCOptTypeWrite:
        case JYTNFCOptTypeExceptRevert:
            !self.writeComplation ?: self.writeComplation(resultSuccess, errorStr, self.cardBalance, self.isGary, self.rechargeFee, self.optStatus == JYTNFCOptStatusBegin);
            break;
        default:
            break;
    }
    [self _changeOptStatus:JYTNFCOptStatusNone];
}

- (void)_startNFCOptWithATS:(NSString *)ats UID:(NSString *)uid API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    [self _requestAdpuResult:[self.prepareCmdResultDict copy] transData:@{} requestType:@"request" ats:ats uid:uid seqNo:@"0" chargeFee:self.rechargeFee orderNo:self.rechargeOrderId cardNo:self.rechargeCardNo checkGreyStatus:YES result:@{} complation:^(BOOL isSuccess, BOOL isFinish, BOOL isGray, NSString *error, BOOL needRewrite) {
        if (isSuccess) {
            if (isFinish) {
                switch (self.optType) {
                    case JYTNFCOptTypeRead:
                        [self _successReadCardWithMessage:@"读卡成功"];
                        break;
                    case JYTNFCOptTypeWrite:
                        [self _successReadCardWithMessage:@"写卡成功"];
                        break;
                    case JYTNFCOptTypeExceptRevert:
                        [self _successReadCardWithMessage:@"重置成功,请稍后"];
                        break;
                    default:
                        break;
                }
            }
        } else {
            [self _failReadCardWithError:error];
        }
    }];
}

- (void)_changeOptType:(JYTNFCOptType)type {
    _optType = type;
}

- (void)_changeOptStatus:(JYTNFCOptStatus)status {
    _optStatus = status;
}

- (void)_changeCardType:(NSString *)cardType {
    _cardTypePath = cardType;
}

- (void)_packageFinishWithCardNo:(NSString *)cardNo balance:(NSString *)cardBalance cityCode:(NSString *)cityCode normalCard:(BOOL)isNormalCard cardStatusStr:(NSString *)cardStatusStr isGary:(BOOL)isGray {
    _cardNo = cardNo;
    _cardBalance = cardBalance;
    _cityCode = cityCode;
    _isNormalCard = isNormalCard;
    _cardStatusStr = cardStatusStr;
    _isGary = isGray;
}

- (void)_requestAdpuResult:(NSDictionary *)adpusResult transData:(NSDictionary *)transData requestType:(NSString *)requestType ats:(NSString *)ats uid:(NSString *)uid seqNo:(NSString *)seqNo chargeFee:(NSString *)chargeFee orderNo:(NSString *)orderNo cardNo:(NSString *)cardNo checkGreyStatus:(BOOL)checkGreyStatus result:(NSDictionary *)result complation:(void(^)(BOOL isSuccess, BOOL isFinish, BOOL isGary, NSString *error, BOOL needRewrite))complation API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    @kWeakify(self);
    [self.api requestCardApdusWithCardTypePath:self.cardTypePath apdusResult:adpusResult optType:self.optType transData:transData requestType:requestType ats:ats uid:uid seqNo:seqNo chargeFee:chargeFee orderNo:orderNo cardNo:cardNo checkGreyStatus:checkGreyStatus result:result complation:^(BOOL isSuccess, BOOL isFinish, NSString *error, NSArray *adpusResultArray, NSDictionary *transData, NSString *requestType, NSString *seqNo, NSString *cardNo, NSString *cardBalance, NSString *cityCode, BOOL isNormalCard, NSString *cardStatusStr, BOOL isGray, NSString *chargeFee, BOOL needRewrite) {
        @kStrongify(self);
        if (isSuccess) {
            if (!isFinish) {
                [self _processAdpus:adpusResultArray complation:^(BOOL finish) {
                    if (finish) {
                        [self _requestAdpuResult:[self.prepareCmdResultDict copy] transData:transData requestType:requestType ats:ats uid:uid seqNo:seqNo chargeFee:self.rechargeFee orderNo:self.rechargeOrderId cardNo:self.rechargeCardNo checkGreyStatus:checkGreyStatus result:result complation:complation];
                    } else {
                        !complation ?: complation(NO, YES, isGray, @"操作失败", needRewrite);
                    }
                }];
            } else {
                NSLog(@"结束了");
                if (adpusResultArray.count > 0) {
                    [self _processAdpus:adpusResultArray complation:^(BOOL finish) {
//                        if (self) {
//                            self->_cardNo = cardNo;
//                            self->_cardBalance = cardBalance;
//                            self->_cityCode = cityCode;
//                            self->_isNormalCard = isNormalCard;
//                            self->_cardStatusStr = [NSString lyIsEmptyStr:cardStatusStr] ? error : cardStatusStr;
//                            self->_isGary = isGray;
//                        }
                        [self _packageFinishWithCardNo:cardNo balance:cardBalance cityCode:cityCode normalCard:isNormalCard cardStatusStr:[NSString lyIsEmptyStr:cardStatusStr] ? error : cardStatusStr isGary:isGray];
                        !complation ?: complation(YES, YES, isGray, @"", needRewrite);
                    }];
                } else {
//                    if (self) {
//                        self->_cardNo = cardNo;
//                        self->_cardBalance = cardBalance;
//                        self->_cityCode = cityCode;
//                        self->_isNormalCard = isNormalCard;
//                        self->_cardStatusStr = [NSString lyIsEmptyStr:cardStatusStr] ? error : cardStatusStr;
//                        self->_isGary = isGray;
//                    }
                    [self _packageFinishWithCardNo:cardNo balance:cardBalance cityCode:cityCode normalCard:isNormalCard cardStatusStr:[NSString lyIsEmptyStr:cardStatusStr] ? error : cardStatusStr isGary:isGray];
                    !complation ?: complation(YES, YES, isGray, @"", needRewrite);
                }
            }
        } else {
            NSLog(@"结束了%@", error);
//            self->_cardStatusStr = [NSString lyIsEmptyStr:cardStatusStr] ? error : cardStatusStr;
//            self->_isNormalCard = NO;
            [self _packageFinishWithCardNo:@"" balance:@"" cityCode:@"" normalCard:NO cardStatusStr:[NSString lyIsEmptyStr:cardStatusStr] ? error : cardStatusStr isGary:NO];
            !complation ?: complation(NO, YES, isGray, error, needRewrite);
        }
    }];
}

- (void)_processAdpus:(NSArray *)adpus complation:(void(^)(BOOL finish))complation API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    BOOL __block finishIn = YES;
    dispatch_queue_t conQueue = dispatch_queue_create("write.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    for (NSInteger i = 0; i < adpus.count; i++) {
        dispatch_sync(conQueue, ^{
            dispatch_group_enter(group);
            NSDictionary *cmdDict = adpus[i];
            if (!finishIn) {
                dispatch_group_leave(group);
            } else {
                [self _writeCmd:cmdDict complation:^(BOOL isSuccess) {
                    finishIn = isSuccess;
                    NSLog(@"写入指令结束 %@", @(isSuccess));
                    dispatch_group_leave(group);
                }];
            }
        });
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"---离开同步组群 %@", @(finishIn));
        !complation ?: complation(finishIn);
    });
}

- (void)_successReadCardWithMessage:(NSString *)message API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    _isNFCSuccess = YES;
    [self _changeOptStatus:JYTNFCOptStatusFinish];
    kGCD_Main_block(^{
        self.nfcSession.alertMessage = message;
        [self.nfcSession invalidateSession];
        self.effective7816Tag = nil;
        self.nfcSession = nil;
    });
}

- (void)_failReadCardWithError:(NSString *)errorStr {
    _isNFCSuccess = NO;
    [self _changeOptStatus:JYTNFCOptStatusFinish];
    _optErrorStr = errorStr;
    if (@available(iOS 13, *)) {
        kGCD_Main_block(^{
            [self.nfcSession invalidateSessionWithErrorMessage:errorStr];
            self.effective7816Tag = nil;
            self.nfcSession = nil;
        });
    }
}

- (void)_writeCmd:(NSDictionary *)cmdDict complation:(void(^)(BOOL isSuccess))complation API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
    NSInteger resultCode = 9000;
    
    NSData *adpuData = [JYTNFCCoreTool convertHexStrToData:[cmdDict lyObjectForKey:@"apdu"]];
    NFCISO7816APDU *cardCmd = [[NFCISO7816APDU alloc] initWithData:adpuData];
    
    if ([[cmdDict lyObjectForKey:@"apdu"] isEqualToString:@"00A404000E325041592E5359532E4444463031"]) {
        //00A404000E325041592E5359532E4444463031 命令特殊处理 直接返回9000
        if (![[cmdDict lyObjectForKey:@"type"] hasSuffix:@"NoReturn"]) {
            [self.prepareCmdResultDict setObject:@"9000" forKey:[cmdDict lyObjectForKey:@"name"]];
        }
        !complation ?: complation(YES);
        return;
    }
    
    NSLog(@"执行指令名称: %@, 指令: %@", [cmdDict lyObjectForKey:@"name"], [cmdDict lyObjectForKey:@"apdu"]);

    @kWeakify(self);
    [self.effective7816Tag sendCommandAPDU:cardCmd completionHandler:^(NSData * _Nonnull responseData, uint8_t sw1, uint8_t sw2, NSError * _Nullable error) {
        @kStrongify(self);
        if (error) {
            NSLog(@"***读取命令%@,失败:%@", [cmdDict lyObjectForKey:@"apdu"], [error localizedDescription]);
            !complation ?: complation(NO);
        } else {
            NSString *tmpResultCode = [NSString stringWithFormat:@"%02x%02x", sw1, sw2];
            if ([[cmdDict lyObjectForKey:@"type"] isEqualToString:@"checkAndReturn"]) {
                //checkAndReturn:检查指令执行完成后返回  域是否为9000，且需要将结果返回到后台服务，返回的结果不带域
                NSLog(@"***命令:%@,读取结果:%@",[cmdDict lyObjectForKey:@"name"], [JYTNFCCoreTool convertApduListDataToHexStr:responseData]);
                NSLog(@"***命令sw域:%@", tmpResultCode);
                if ([tmpResultCode integerValue] != resultCode) {
                    !complation ?: complation(NO);
                } else {
                    [self.prepareCmdResultDict setObject:[JYTNFCCoreTool convertApduListDataToHexStr:responseData] forKey:[cmdDict lyObjectForKey:@"name"]];
                    !complation ?: complation(YES);
                }
            } else if ([[cmdDict lyObjectForKey:@"type"] isEqualToString:@"noCheckReturn"]) {
                //noCheckReturn：不检查指令执行完成后返回 域是否为9000，需要将结果返回到后台服务
                //读取成功
                [self.prepareCmdResultDict setObject:[NSString stringWithFormat:@"%@%@", [JYTNFCCoreTool convertApduListDataToHexStr:responseData], tmpResultCode] forKey:[cmdDict lyObjectForKey:@"name"]];
                NSLog(@"***命令:%@,读取结果:%@",[cmdDict lyObjectForKey:@"name"], [JYTNFCCoreTool convertApduListDataToHexStr:responseData]);
                NSLog(@"***命令sw域:%@", tmpResultCode);
                !complation ?: complation(YES);
            } else if ([[cmdDict lyObjectForKey:@"type"] isEqualToString:@"checkNoReturn"]) {
                NSLog(@"***命令:%@,读取结果:%@",[cmdDict lyObjectForKey:@"name"], [JYTNFCCoreTool convertApduListDataToHexStr:responseData]);
                NSLog(@"***命令sw域:%@", tmpResultCode);
                if ([tmpResultCode integerValue] == resultCode) {
                    //读取成功
                    !complation ?: complation(YES);
                } else {
                    //读取失败，直接退出，并且清空prepareCmdRetArray数据
                    !complation ?: complation(NO);
                }
            } else {
                NSLog(@"***命令:%@,读取结果:%@",[cmdDict lyObjectForKey:@"name"], [JYTNFCCoreTool convertApduListDataToHexStr:responseData]);
                NSLog(@"***命令sw域:%@", tmpResultCode);
                !complation ?: complation(YES);
            }
        }
    }];
}

- (NSMutableDictionary *)prepareCmdResultDict {
    if (!_prepareCmdResultDict) {
        _prepareCmdResultDict = NSMutableDictionary.new;
    }
    return _prepareCmdResultDict;
}

- (JYTNFCApi *)api {
    if (!_api) {
        _api = JYTNFCApi.new;
    }
    return _api;
}

@end
